// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import ColorConfig from "../models/ColorConfig";

const {ccclass, property} = cc._decorator;

const defaultColor = cc.color(180, 180, 180);

@ccclass
export default class StockItem extends cc.Component {

    @property(cc.Label)
    labelName: cc.Label = null;

    @property(cc.Label)
    labelFloat: cc.Label = null;

    stockInfo: any = null;
    
    @property(cc.Node)
    frontNode: cc.Node = null;

    protected onLoad(): void {
        cc.director.on('SetGatherColor', this.onSetGatherColor, this);
    }

    protected onDestroy(): void {
        cc.director.off('SetGatherColor', this.onSetGatherColor, this);
    }

    onSetGatherColor (params) {
        if (this.node.opacity == 0) return;
        let key = this.stockInfo.ts_code;
        if (params[key] == null) return;
        this.frontNode.color = params[key];
    }

    setItemData (info: any) {
        this.stockInfo = info;
        if (info.date) {
            this.setName(info.date);
            this.labelFloat.string = '';
            this.node.color = cc.color(180, 0, 0);
            this.frontNode.color = defaultColor;
        } else {
            this.setName(info.name);
            if (info.change === null) {
                this.labelFloat.string = '空数据';
                this.node.color = cc.color(0, 0, 0);
            } else {
                this.setFloat(info.change);
                if (info.change >= 0) {
                    this.node.color = cc.color(180, 0, 0);
                } else {
                    this.node.color = cc.color(0, 150, 0);
                }
            }
            let color = ColorConfig.getModule().getColor(info.ts_code);
            if (color) {
                this.frontNode.color = color;
            } else {
                this.frontNode.color = defaultColor;
            }
        }        
    }

    setName (name) {
        this.labelName.string = name;
    }

    setFloat (pct: number) {
        if (pct >= 0) {
            this.labelFloat.string = Math.abs(Math.floor(pct * 100) / 100) + '%';
        } else {
            this.labelFloat.string =  '-' + Math.abs(Math.floor(pct * 100) / 100) + '%';
        }
        
    }

    onClick () {
        if (this.node.opacity == 0) return;
        if (this.stockInfo.date) {
            cc.director.emit('ClickStockDate', this.stockInfo.date);
        } else {
            cc.director.emit('ClickStockItem', this.stockInfo);
        }
    }
}
